<?php
//-------------------------------------------------------------------------------------------------------
	require_once(dirname(__FILE__).'/../config.inc.php');
    require_once($config['app_dir'] . '/includes/template.class.php');
    require_once($config['app_dir'] . '/classes/class.timezone.php');
    require_once($config['app_dir'] . '/includes/db.class.php');
    require_once($config['app_dir'] . '/includes/auxiliary.class.php');
    require_once($config['app_dir'] . '/classes/stockplot.data.php');
    require_once($config['app_dir'] . '/classes/tracks.class.php');
    //---------------------------------------------------------------------------------------------------
    class objFlashCandleServer extends objTrackForecastsShow {
                  protected $_data = false;
                  protected $action;
                  protected $StockModel;
                  protected $_sql_querys = array();
				  public $showActive;
                  public $userID;
                  public $XMLEnabled = true;
                  public $TXTEnabled = true;
                  public $XMLFolderPath;
                  public $XMLHTTPPath;
                  public $candleData;
                  public $pairCode;
                  public $timeFrame;
                  public $timeFrameAbbr;
                  public $system;
                  public $daysPeriod;
                  public $entryPoint;
                  public $entry;
                  public $tradeID;
                  public $defaultPeriod = 30;
                  public $updateFcastData = array();

         public function __construct($action=false, $pairCode, $timeFrame, $userID=false, $systemID=false, $days=false, $entry=false, $fsw=false, $fid=false, $showActive=false) {
         	if (!$action) $this->action = "get_last_days";
         	else $this->action = $action;
			
			$this->showActive = $showActive;

         	$this->pairCode = $pairCode;

         	$this->updateFcastData['sw']['id'] = $fsw;
         	$this->updateFcastData['id']['id'] = $fid;

         	if (!$timeFrame) {
         		$this->timeFrame = 240;
         	    $timeFrame = "h4";
         	} else $this->timeFrame = objAuxiliary::convertTimeframeFromAbbr($timeFrame); //in minutes
         	$this->timeFrameAbbr = strtolower($timeFrame);
         	$this->userID = $userID;
         	if (!$systemID) $this->system = 4;
         	else $this->system = $systemID;

			// set days period to select candles
			if ($days) $this->daysPeriod = $days;
			else $this->daysPeriod = $this->defaultPeriod;
			$this->entry = $entry;
			if (!$this->entry) $this->entryPoint = "UNIX_TIMESTAMP()";
        	else $this->entryPoint = $this->entry;

         	$this->tradeID = $this->getTradeFromRequest();

			global $config;
         	$this->XMLFolderPath = $config['app_dir'].'\public_html\xml\\';
         	$this->XMLHTTPPath = $config['host']['root'].'xml/';

         	$this->_db = objDataBase::GetInstance();
          	$this->_sqls();
         }//constructor


         protected function getTimezoneOffset() {
         	// get time offset depending on user timezone. Offset = 0 if no user id passed
         	$objTimezone = new objTimezone();
         	if (!$this->userID) $offset = 0;
         	else $offset = $objTimezone->getOffsetByUserId($this->userID);
           	return $offset;
         } //getTimezoneOffset


         protected function getTradeFromRequest() {
         	$converter = new objAuxiliary();
           	return $converter->getPairIDTF($this->timeFrame, $this->pairCode);

         } //getTradeFromRequest

         // process forecast data from DB and prepare for flash params
         protected function updateForecast($dbResult,$system) {
         	$updateFcast = array();

			//echo $dbResult['ForecastID']." ".$dbResult['TradeID']." - ".$this->tradeID."<br>";

         	if ($dbResult['maxID'.$system]>=$dbResult['ForecastID'] && $dbResult['TradeID']==$this->tradeID) $updateFcast['last'] = 1;
         	else $updateFcast['last'] = 0;

         	$updateFcast['profit'] = $dbResult['Profit'];
         	$updateFcast['active'] = $dbResult['FlagActive'];

         	if (!$dbResult['FlagActive']) {
         		$updateFcast['status'] = "Closed trade";
         		$updateFcast['profitlabel'] = "NET P/L";

         	} else {
         		$updateFcast['status'] = "Trading...";
         		$updateFcast['profitlabel'] = "Floating P/L";
         	}

         	if($dbResult['BeginPrice']>10) $updateFcast['pipsize'] = 0.01;
         	else $updateFcast['pipsize'] = 0.0001;

         	if(!$dbResult['EndTime']) $updateFcast['endtime'] = $dbResult['BeginTime']+3600*8;
         	else $updateFcast['endtime'] = $dbResult['EndTime'];

			if(!$dbResult['EndTime']) $updateFcast['endtimef'] = " -";
         	else $updateFcast['endtimef'] = date("m.d h:i A", $endtime)." GMT";



           	return $updateFcast;

         } //Forecast


         protected function processCandle($dbResult) {
         	$candleData = array(
				//'debug' => date("Y-m-d G:i",$dbResult['TimeStart']),
            	't' => ($dbResult['TimeStart'])/100,
            	'o' => $dbResult['O'],
            	'h' => $dbResult['H'],
                'l' => $dbResult['L'],
                'c' => $dbResult['C'],
                'psw' => round($this->updateFcastData['sw']['data']['profit']),
                'pid' => round($this->updateFcastData['id']['data']['profit']),
                'asw' => round($this->updateFcastData['sw']['data']['active']),
                'aid' => round($this->updateFcastData['id']['data']['active']),
                'lastsw' => round($this->updateFcastData['sw']['data']['last']),
                'lastid' => round($this->updateFcastData['id']['data']['last'])
                //'v' => $dbResult['V']
            );
           	return $candleData;

         } //processCandle


         protected function processForecast($dbResult) {

         	if (!$dbResult['FlagActive']) {
         		$tradeStatus = "Closed trade";
         		$profitLabel = "NET P/L";

         	} else {
         		$tradeStatus = "Trading...";
         		$profitLabel = "Floating P/L";
         	}

         	if($dbResult['BeginPrice']>10) $pipSize = 0.01;
         	else $pipSize = $pipSize=0.0001;

         	if(!$dbResult['EndTime']) $endtime = $dbResult['BeginTime']+3600*8;
         	else $endtime = $dbResult['EndTime'];

			if(!$dbResult['EndTime']) $endtimeFormatted = " -";
         	else $endtimeFormatted = date("m.d h:i A", $endtime)." GMT";


         	$orderType = "[MARKET ORDER]";

         	if ($dbResult['Side']==1) {
         		$orderAction = "SELL";
         		$negativeSign = (-1);
         	} else {
         		$orderAction = "BUY";
         		$negativeSign = 1;
         	}

         	$forecastsData = array(
				//'debug' => $dbResult['BeginTime']." ".$endtime,
         		'id' => objAuxiliary::getSystemShortName($this->system).$dbResult['ForecastID'],
            	'bp' => $dbResult['BeginPrice'],
            	'bt' => $dbResult['BeginTime'],
            	//'btl' => date("Y-m-d h:i A", $dbResult['BeginTime'])." GMT",
				'btl' => date("m.d h:i A", $dbResult['BeginTime'])." GMT",
            	'ep' => $dbResult['EndPrice'],
            	'epp' => intval(($negativeSign * ($dbResult['EndPrice'] - $dbResult['BeginPrice'])) / $pipSize),
                'et' => $endtime,
				'etl' => $endtimeFormatted,
                'sp' => $dbResult['StopPrice'],
                'spp' => intval(($negativeSign * ($dbResult['StopPrice'] - $dbResult['BeginPrice'])) / $pipSize),
                'cp' => $dbResult['ClosePrice'],
                'ct' => $dbResult['CloseTime'],
                //'ctl' => date("Y-m-d h:i A", $dbResult['CloseTime'])." GMT",
				'ctl' => date("m.d h:i A", $dbResult['CloseTime'])." GMT",
                'c' => $dbResult['Color'],
                's' => $dbResult['Side'],
                'p' => intval($dbResult['Profit']),
                'pl' => $profitLabel,
                'status' => $tradeStatus,
                'act' => $orderAction,
                //'side' => $dbResult['Side'],
                'type' => $orderType
            );
           	return $forecastsData;

         } //Forecast


         protected function getLastCandle() {
         	//$this->_db->handler->debug = true;
            $rs = $this->_db->handler->Execute($this->_sql_querys['get_last_candle'], array($this->pairCode, $this->timeFrame, $this->pairCode, $this->timeFrame));

			// get forecasts data
            $rsFcast = $this->_db->handler->Execute($this->_sql_querys['get_forecast_by_id'], array($this->updateFcastData['sw']['id'], $this->updateFcastData['id']['id']));
            while (!$rsFcast->EOF) {
            	if ($rsFcast->fields['SystemID']==1) $this->updateFcastData['sw']['data'] = $this->updateForecast($rsFcast->fields,1);
            	else if ($rsFcast->fields['SystemID']==4) $this->updateFcastData['id']['data'] = $this->updateForecast($rsFcast->fields,4);
				$rsFcast->MoveNext();
			}

           	$this->candleData = array($this->processCandle($rs->fields));
           	//echo count($this->processCandle($rs->fields));
           	return $this->candleData;
         } //getLastCandle


         protected function getPeriodCandles() {
         	//$this->_db->handler->debug = true;
         	$this->candleData = array();
            $rs = $this->_db->handler->Execute($this->_sql_querys['get_last_days'], array($this->pairCode, $this->timeFrame, $this->daysPeriod));

            //echo date("Y-m-d",($rs->fields['cTime']-86400*$this->daysPeriod))." - ".date("Y-m-d",$rs->fields['cTime'])." ".$rs->fields['cTime'];

            while(!$rs->EOF){
            	$this->candleData[] = $this->processCandle($rs->fields);
                $rs->MoveNext();
            }

           	return $this->candleData;
         } //getLastCandle


         protected function getPeriodForecasts() {
         	//$this->_db->handler->debug = true;
         	$this->candleData = array();
         	$tradeID = '2400'.$this->pairCode; //old template for tradeID
         	$tStart = date("Y-m-d",(time()-86400*$this->daysPeriod)); // '2008-03-20'
         	$tFinish = date("Y-m-d",time()); //'2008-04-08'
         	//echo $tStart." - ".$tFinish."<br>";
         	$trackForecasts = new objTrackForecastsShow($tradeID, $tStart, $tFinish, $this->system);
         	$trackForecasts->enable_active = true;

			foreach($trackForecasts->Prepare() as $fcastitem){
				if ($this->showActive) {
					$this->candleData[] = $this->processForecast($fcastitem);
				} else if (!$fcastitem['FlagActive']) {
					$this->candleData[] = $this->processForecast($fcastitem);
				}
            	//var_dump($fcastitem);
            	//echo "<br><br><br>";
            }


         	//$rs = $this->_db->handler->getAll($trackForecasts->_sql_querys['forecast_list']);
            //$rs = $this->_db->handler->Execute($this->_sql_querys['get_forecasts_days'], array($this->pairCode, $this->daysPeriod));
            //while(!$rs->EOF){
            	//$this->candleData[] = $this->processForecast($rs->fields);
                //$rs->MoveNext();
            //}

           	return $this->candleData;
         } //getLastCandle


         protected function generateParamsText($aData) {
         	$paramsArray = array();
            foreach($aData as $key => $value){
              	$paramsArray[] = "$key=$value";
            }
            $paramsString = implode('&',$paramsArray);
           	return $paramsString;
         } //generateCandleParams


         protected function generateParamsXML($emptyCandle, $candleData) {
         	foreach ($candleData as $param=>$val){
         		$emptyCandle->addAttribute($param, $val);
         	}
           	//return $candles;
         } // generateCandleParamsXML


         public function generateXMLFile($fileName) {
         	if ($this->action == "get_forecasts_days") {
         		$objXMLFile = simplexml_load_string('<forecasts></forecasts>');
         		$childTag = "item";
         	} else {
         		$objXMLFile = simplexml_load_string('<candles></candles>');
         		$childTag = "c";
         	}
          	//echo gettype($this->candleData);
         	//add child C tag and than add necessary attributes to it
            foreach ($this->candleData as $candleitem){
            	$emptyCandle = $objXMLFile->addChild($childTag);
            	$this->generateParamsXML($emptyCandle, $candleitem);
            }
           	//return $objXMLFile->asXML($fileName);
           	return $objXMLFile->asXML(); //return xml not file
         } //generateXMLFile



         public function ProcessRequest() {
         	//if( !$this->action) exit("define all required params");
         	$filenamePrefix = $this->XMLFolderPath.$this->timeFrameAbbr."_".$this->pairCode;
         	$filenameHttpPrefix = $this->XMLHTTPPath.$this->timeFrameAbbr."_".$this->pairCode;

			switch ($this->action) {

			// request for last candle
			case "get_last_candle":
				$this->getLastCandle();
				if ($this->TXTEnabled) echo $this->generateParamsText($this->candleData[0]);
				//if ($this->XMLEnabled) $this->generateXMLFile ( $filenamePrefix.'_last_candle.xml' );
				break;

			// request for candle for several days
			case "get_last_days":
				$this->getPeriodCandles();
                //echo count($this->candleData)." ";
                if ($this->XMLEnabled) {
					$fileName = $filenamePrefix.'_last_'.$this->daysPeriod.'.xml';
					$fileNameHttp = $filenameHttpPrefix.'_last_'.$this->daysPeriod.'.xml';
					//$this->generateXMLFile ( $fileName );
					//echo $fileNameHttp;
					echo $this->generateXMLFile ( $fileName );
				}
				break;

			// request for forecasts for several days
			case "get_forecasts_days":
				$this->getPeriodForecasts();
				$fileName = $filenamePrefix.'_forecasts_'.$this->daysPeriod.'.xml';
				$fileNameHttp = $filenameHttpPrefix.'_forecasts_'.$this->daysPeriod.'.xml';
				//echo $fileNameHttp;
                //echo count($this->candleData)." ";
				//if ($t	his->TXTEnabled) echo $this->generateCandleParamsText($this->candleData);
				//if ($this->XMLEnabled) echo $this->generateXMLFile ( $fileName );
				echo $this->generateXMLFile ( $fileName );

				break;
			}
   			return true;
         } //ProcessRequest

         protected function _sqls() {
            $this->_sql_querys['rates'] =
               "SELECT *, FROM_UNIXTIME((r.`Time`+?), '%Y-%m-%d %H:%i:%s') as RateTime FROM fa_rates r ORDER BY r.SortIndex";
            $this->_sql_querys['get_last_candle'] =
               "SELECT * FROM fa_quotes WHERE SymbolCode=? AND TimeFrame=? AND TimeStart=".
               "(SELECT MAX(TimeStart) FROM fa_quotes WHERE SymbolCode=? AND TimeFrame=?)";
            $this->_sql_querys['get_last_days'] =
               "SELECT TradeID, TimeStart, O, H, L, C, V, ".$this->entryPoint." as cTime FROM fa_quotes ".
               "WHERE SymbolCode=? AND TimeFrame=? AND TimeStart BETWEEN (".$this->entryPoint."-86400*?) and ".$this->entryPoint.
               " ORDER BY TimeStart asc";
            // query currently not used
            $this->_sql_querys['get_forecasts_days'] =
               "SELECT f.BeginPrice, f.BeginTime, f.EndPrice, f.EndTime, f.StopPrice, f.ClosePrice, f.CloseTime, t.SymbolCode, ".
               "round((1 - 2 * f.Side) * (f.ClosePrice - f.BeginPrice) / t.PipSize) as Profit, (f.CloseTime is null) as FlagActive".
               " FROM vfa_forecast f LEFT JOIN fa_trades t ON t.TradeID=f.TradeID ".
               "WHERE t.SymbolCode=? AND BeginTime BETWEEN (".$this->entryPoint."-86400*?) and ".$this->entryPoint.
               " ORDER BY BeginTime asc";
            $this->_sql_querys['get_forecast_by_id1'] =
               "SELECT f.BeginPrice, f.BeginTime, f.EndPrice, f.EndTime, f.StopPrice, f.ClosePrice, f.CloseTime, t.SymbolCode, f.SystemID, ".
               "round((1 - 2 * f.Side) * (f.ClosePrice - f.BeginPrice) / t.PipSize) as Profit, (f.CloseTime is null) as FlagActive".
               " FROM vfa_forecast f LEFT JOIN fa_trades t ON t.TradeID=f.TradeID ".
               "WHERE f.ForecastID=? OR f.ForecastID=?";


               $this->_sql_querys['get_forecast_by_id'] =
            " SELECT f.ForecastID, (f.CloseTime is null) as FlagActive, f.BeginPrice, f.BeginTime,f.EndPrice,f.EndTime,t.PipSize, t.TradeID,t.Pair, f.Color, f.StopPrice, f.Side,f.SystemID, f.ClosePrice, f.CloseTime, f.TradeID, ".
            "(SELECT max(m1.ForecastID) FROM vfa_forecast m1 WHERE m1.SystemID=1) as maxID1, ".
            "(SELECT max(m4.ForecastID) FROM vfa_forecast m4 WHERE m4.SystemID=4) as maxID4, ".

                    " round((1 - 2 * f.Side) * (COALESCE(f.ClosePrice, (1-f.Side)* r.Bid + f.Side*r.Ask, lq.LastClosePrice) - f.BeginPrice) / t.PipSize) as Profit, ".
                " COALESCE(f.CloseTime,lq.LastCloseTime) as CloseTime,   ".
                " COALESCE(f.ClosePrice,lq.LastClosePrice) as ClosePrice   ".

            " FROM vfa_forecast f ".
                   " LEFT OUTER JOIN fa_trades t ON (f.TradeID = t.TradeID) ".
                   " LEFT OUTER JOIN fa_rates r  ON (f.TradeID=r.TradeID)  ".
                   " LEFT OUTER JOIN ".
                     "(  ".
                      " SELECT ".
                           " ttq.TradeID, ".
                           " ttq.C as LastClosePrice, ".
                           " ttq.TimeStart as LastCloseTime ".
                      " FROM fa_quotes ttq ".
                          " RIGHT OUTER JOIN ( ".
                                " SELECT tq.TradeID, max(tq.TimeStart) as max_quote_time ".
                                " FROM fa_quotes tq ".
                                " GROUP BY tq.TradeID) qq ".
                                " ON (qq.max_quote_time=ttq.TimeStart and qq.TradeID=ttq.TradeID) ".
                    " ) lq ".
                    " ON (f.TradeID = lq.TradeID) ".
					 "WHERE f.ForecastID=? OR f.ForecastID=?";
         } //_sqls

    } //class objFlashCandleServer


    /////////////////////////////////////////////////////////////////////////////////////////////////


    class objFlashForecastServer extends objStockModel {
                  protected $_data = false;
                  protected $action;
                  protected $StockModel;
                  protected $_sql_querys = array();
                  public $userID;
                  public $XMLEnabled = true;
                  public $TXTEnabled = true;

         public function __construct($action, $pairCode, $tStart=false, $tFinish=false, $aSystem) {
         	$this->action = $action;
         	$this->pairID = $pairCode;
         	$this->tStart = $tStart;
         	$this->tFinish = $tFinish;
         	$this->system = $aSystem;


         	$this->_db = objDataBase::GetInstance();
          	$this->_sqls();
         }//constructor


         public function getForecastData() {
         	//$StockModel = new objStockModel($this->pairID, $this->tStart, $this->tFinish, $aID=false, $this->system);
         	$StockModel = new objStockModel($this->pairID, '1171368960', '1171446120', $aID=false, $this->system);
         	//$StockModel = new objStockModel($this->pairID, 2007-01-01, 2008-04-01, $aID=false, $this->system);
         	$StockModel->StrongInterval(false);
            $StockModel->SetNews(false);
         	//$StockModel->Prepare();
           	return $StockModel->GetLastForecast();
         } //getTradeFromRequest


         protected function _sqls() {

         } //_sqls

    } //class objLastRateServer



    //---------------------------------------------------------------------------------------------------
    /*
    function showLastRates($userID=false) {

         $objResponse = new xajaxResponse();
	 	$objResponse->addAssign("divRates","innerHTML", $LastRateServer->Render());

         return $objResponse;
    }//showLastRates

	objAuxiliary::convertTimeframeFromAbbr($tfAbbr);

    GetBody($aLang, objStockModel $StockModel, $messagetype, $flagCaching=false, $aID=false, $trade_mode=false)
    $StockModel = new objStockModel($this->trade, $this->start, $this->finish, false, $this->system);


    */


    function flashReloadHandler() {

         $objResponse = new xajaxResponse();
	 	$objResponse->addAssign("lashReload","innerHTML", InsertFlash());

         return $objResponse;
    }//showLastRates
//-------------------------------------------------------------------------------------------------------
?>